package com.network.service;

import com.network.dao.PlanDao;
import com.network.entity.Plan;
import com.network.entity.User;
import com.network.qo.PageQo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@CacheConfig(cacheNames = "plans")
public class PlanService
{
    @Autowired
    PlanDao planDao;

    @Cacheable
    public List<Plan> getAll()
    {
        return planDao.findAll();
    }

    public CompletableFuture<Plan> save(Plan plan)
    {
        return CompletableFuture.supplyAsync(() -> {
             Plan plan1= planDao.save(plan);
             return plan1;
        });
    }


    public Page<Plan> findPlanByPage(PageQo pageQo)
    {
        //根据创建时间排序
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");

        Pageable pageable=new PageRequest(pageQo.getPage(),pageQo.getLimit(),sort);
        return planDao.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> predicateList=new ArrayList<Predicate>();
            query.where(predicateList.toArray(new Predicate[predicateList.size()]));
            return query.getRestriction();
        },pageable);
    }


    public void delPlanById(Long id)throws Exception
    {
          planDao.delete(id);
    }

    public Plan getPlanById(Long id)
    {
        return planDao.findFirstById(id);
    }
}
